package com.songxh.shared.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author songxh
 * @create 2023-01-10-14:16
 */
@Configuration
@EnableAsync  //配合@Async注解使用，进行异步处理
public class ThreadPoolConfig {

    public final static String VIEW_COUNT_ASYNC_NAME = "VIEW_COUNT_ASYNC_NAME";

    /**
     * 创建一个通用线程池
     * @return
     */
    @Bean(VIEW_COUNT_ASYNC_NAME)
    public Executor asyncServiceExecutor(){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //核心线程池大小:防止异步并发处理,线程池设置为1
        executor.setCorePoolSize(1);
        //最大线程数
        executor.setMaxPoolSize(5);
        //队列容量:初期数量大
        executor.setQueueCapacity(4000);
        //活跃时间
        executor.setKeepAliveSeconds(60);
        //线程名字前缀
        executor.setThreadNamePrefix("commonTask-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
}
